import Vue from 'vue'
import VueRouter from 'vue-router'

Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    name: 'index',
    // route level code-splitting
    // this generates a separate chunk (Login.[hash].js) for this route
    // which is lazy-loaded when the route is visited.
    component: () => import(/* webpackChunkName: "Login" */ '../views/luggage.vue')
  },
  {
    path: '/login',
    name: 'Login',
    // route level code-splitting
    // this generates a separate chunk (Login.[hash].js) for this route
    // which is lazy-loaded when the route is visited.
    component: () => import(/* webpackChunkName: "Login" */ '../views/Login.vue')
  },
  {
    path: '/luggage',
    name: 'luggage',
    component: () => import(/* webpackChunkName: "Login" */ '../views/luggage')
  },
  {
    path: '/luggage/add',
    name: 'loggage_add',
    component:  () => import(/* webpackChunkName: "Login" */ '../views/luggageAdd')
  },
  {
    path: '/oauth2/login',
    name: 'oauth2_login',
    component:  () => import(/* webpackChunkName: "Login" */ '../views/oauth2/login')
  },
  {
    path: '/oauth2/callback',
    name: 'oauth2_callback',
    component:  () => import(/* webpackChunkName: "Login" */ '../views/oauth2/oauthCallBack')
  },
  {
    path: '/register',
    name: 'register',
    component:  () => import(/* webpackChunkName: "Login" */ '../views/register')
  },
  {
    path: '/oauth2/client/list',
    name: 'oauth2_client_list',
    component:  () => import(/* webpackChunkName: "Login" */ '../views/oauth2/client-list')
  },
  {
    path: '/oauth2/client/add',
    name: 'oauth2_client_add',
    component:  () => import(/* webpackChunkName: "Login" */ '../views/oauth2/client-add')
  },
  {
    path: '*',
    name: 'error',
    component:  () => import(/* webpackChunkName: "Login" */ '../views/Error')
  },
]
//前置路由守卫
const router = new VueRouter({
  mode: 'history',
  history: 'history',
  base: process.env.BASE_URL,
  routes
})
router.beforeEach((to, from, next) => {
  var token =localStorage.getItem('token')

  if(to.name === 'Login' && token) {
    // 如果用户未能验证身份，则 `next` 会被调用两次
    next({path: '/'})
  }

  if (to.name !== 'Login' && to.name !== 'oauth2_login' && to.name !== 'oauth2_callback' && to.name !== 'register' && !token) {
    next({name: 'Login', query: { redirect_uri: to.path}})
  }
  next()
})
export default router
